package com.kaily.imagelib.element;

import android.graphics.Bitmap;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;

import com.kaily.imagelib.BaseApplication;
import com.kaily.imagelib.utils.BitmapUtils;

/**
 * 头像元素
 *
 * @date 2018/10/21 下午9:14
 * @author: kaily_zhou
 */
public class AvatarElement extends ImageElement {
    private static final String TAG = "AvatarElement";
    private Bitmap defaultIcon;
    private boolean isNeedDefaultIcon;
    private static final int DEFAULT_SIZE = 100;

    public AvatarElement(Bitmap defaultIcon, String imgUrl, boolean isRequireElement, float left, float top, int width, int height) {
        this(defaultIcon, imgUrl, isRequireElement, left, top, width, height, false);
    }

    public AvatarElement(Bitmap defaultIcon, String imgUrl, boolean isRequireElement, float left, float top, int width, int height, boolean isNeedDefaultIcon) {
        super(imgUrl, isRequireElement, left, top, width, height);
        this.defaultIcon = defaultIcon;
        this.isNeedDefaultIcon = isNeedDefaultIcon;
    }

    @Override
    public boolean generateElement() {

        if (!TextUtils.isEmpty(imgUrl)) {
            try {
                bitmap = Glide.with(BaseApplication.getAppContext())
                        .load(imgUrl)
                        .asBitmap()
                        .centerCrop()
                        .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
            } catch (OutOfMemoryError outOfMemoryError) {
                if (isNeedDefaultIcon && bitmap == null) {
                    bitmap = defaultIcon;
                }
            } catch (Exception e) {
                bitmap = null;
            }
        } else {
            bitmap = defaultIcon;
        }

        if (bitmap == null) {
            return !isRequireElement;
        }
        int size = 0;
        if (width > 0 || height > 0) {
            size = Math.max(width, height);
        } else {
            size = DEFAULT_SIZE;
        }
        bitmap = BitmapUtils.createCircleImage(bitmap, size);
        if (bitmap == null) {
            return !isRequireElement;
        }
        return true;
    }
}
